<template>
    <div id="cesiumContainer" style="width: 100%; height: 100%;">
        <div v-if="selectedPoint" class="point-popup" :style="popupStyle">
            <div class="popup-header">
                <span>点位信息</span>
                <span class="close-btn" @click="selectedPoint = null">×</span>
            </div>
            <div class="popup-content">
                <p>编号: {{ selectedPoint.id }}</p>
                <p>经度: {{ selectedPoint.longitude.toFixed(6) }}°</p>
                <p>纬度: {{ selectedPoint.latitude.toFixed(6) }}°</p>
            </div>
        </div>
    </div>
</template>
    
<script setup lang='ts'>
import { Viewer, Terrain, Cartesian3, WebMapTileServiceImageryProvider, ImageryLayer, Color, Entity, ClassificationType, VerticalOrigin, LabelStyle, HeightReference, ScreenSpaceEventHandler, ScreenSpaceEventType, defined } from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'; 
import { onMounted, ref } from 'vue';

interface PointInfo {
    id: number;
    longitude: number;
    latitude: number;
}

// 天地图token
const tdtToken = "6e2a72be0fdce02f599e7f4b33d5b01a";

// 选中的点位信息
const selectedPoint = ref<PointInfo | null>(null);
const popupStyle = ref({
    left: '0px',
    top: '0px'
});

// 重庆市的大致边界坐标点（简化版）
const chongqingBoundary = [
    [106.28, 31.85],
    [106.57, 31.48],
    [107.12, 31.49],
    [107.31, 31.31],
    [108.67, 31.49],
    [108.92, 31.83],
    [109.10, 31.75],
    [109.37, 31.90],
    [109.47, 31.65],
    [109.77, 31.65],
    [110.00, 31.23],
    [109.76, 30.89],
    [109.51, 30.93],
    [109.21, 30.57],
    [109.07, 30.34],
    [108.81, 30.27],
    [108.62, 30.34],
    [108.43, 29.91],
    [108.14, 29.91],
    [107.94, 29.60],
    [107.64, 29.48],
    [107.34, 29.58],
    [107.15, 29.38],
    [106.85, 29.45],
    [106.65, 29.22],
    [106.41, 29.18],
    [106.24, 29.37],
    [105.86, 29.34],
    [105.75, 29.51],
    [105.89, 29.85],
    [105.72, 30.13],
    [105.86, 30.47],
    [106.11, 30.54],
    [106.15, 30.81],
    [105.93, 31.08],
    [106.06, 31.33],
    [106.28, 31.85]
];

// 计算重庆市的经纬度范围
const lonMin = Math.min(...chongqingBoundary.map(point => point[0]));
const lonMax = Math.max(...chongqingBoundary.map(point => point[0]));
const latMin = Math.min(...chongqingBoundary.map(point => point[1]));
const latMax = Math.max(...chongqingBoundary.map(point => point[1]));

// 生成随机点的函数
function generateRandomPoints(count: number): [number, number][] {
    const points: [number, number][] = [];
    for (let i = 0; i < count; i++) {
        const lon = lonMin + Math.random() * (lonMax - lonMin);
        const lat = latMin + Math.random() * (latMax - latMin);
        points.push([lon, lat]);
    }
    return points;
}

onMounted(() => {
    const viewer = new Viewer('cesiumContainer',{
        terrain: Terrain.fromWorldTerrain(),
        animation: false,
        timeline: false,
        baseLayerPicker: false,
        fullscreenButton: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        infoBox: false,
        selectionIndicator: false,
    });

    // 配置相机控制
    const controller = viewer.scene.screenSpaceCameraController;
    controller.enableRotate = false;     // 禁用旋转
    controller.enableTilt = false;       // 禁用倾斜
    controller.enableLook = false;       // 禁用视角调整
    controller.enableTranslate = true;   // 启用平移
    controller.enableZoom = true;        // 启用缩放

    // 添加天地图影像底图
    const imageryProvider = new WebMapTileServiceImageryProvider({
        url: `http://t0.tianditu.gov.cn/img_w/wmts?tk=${tdtToken}`,
        layer: 'img',
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'w',
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
        maximumLevel: 18
    });
    viewer.imageryLayers.addImageryProvider(imageryProvider);

    // 添加天地图国界
    const labelImageryProvider = new WebMapTileServiceImageryProvider({
        url: `http://t0.tianditu.gov.cn/cia_w/wmts?tk=${tdtToken}`,
        layer: 'cia',
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'w',
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    });
    viewer.imageryLayers.addImageryProvider(labelImageryProvider);

    // 绘制重庆市边界
    const positions = chongqingBoundary.map(coord => 
        Cartesian3.fromDegrees(coord[0], coord[1])
    );

    // 添加边界线
    viewer.entities.add({
        polyline: {
            positions: positions,
            width: 2,
            material: Color.YELLOW,
            clampToGround: true
        }
    });

    // 添加面
    viewer.entities.add({
        polygon: {
            hierarchy: positions,
            material: Color.RED.withAlpha(0.3),
            outline: true,
            outlineColor: Color.YELLOW,
            outlineWidth: 2,
            classificationType: ClassificationType.TERRAIN
        }
    });

    // 生成50个随机点并添加到地图上
    const randomPoints = generateRandomPoints(20);
    const pointEntities = randomPoints.map((point, index) => {
        return viewer.entities.add({
            position: Cartesian3.fromDegrees(point[0], point[1], 0),
            point: {
                pixelSize: 10,
                color: Color.RED,
                outlineColor: Color.WHITE,
                outlineWidth: 2,
                heightReference: HeightReference.CLAMP_TO_GROUND
            },
            label: {
                text: `点${index + 1}`,
                font: '14px sans-serif',
                fillColor: Color.WHITE,
                outlineColor: Color.BLACK,
                outlineWidth: 2,
                style: LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: VerticalOrigin.BOTTOM,
                pixelOffset: new Cartesian3(0, -15, 0),
                heightReference: HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            // 存储点位信息用于弹窗显示
            properties: {
                id: index + 1,
                longitude: point[0],
                latitude: point[1]
            }
        });
    });

    // 添加点击事件处理
    const handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction((movement: any) => {
        const pickedObject = viewer.scene.pick(movement.position);
        if (defined(pickedObject) && pickedObject.id) {
            const entity = pickedObject.id;
            if (entity.properties) {
                const props = entity.properties;
                selectedPoint.value = {
                    id: props.id._value,
                    longitude: props.longitude._value,
                    latitude: props.latitude._value
                };
                // 设置弹窗位置
                popupStyle.value = {
                    left: `${movement.position.x + 10}px`,
                    top: `${movement.position.y - 10}px`
                };
            }
        } else {
            selectedPoint.value = null;
        }
    }, ScreenSpaceEventType.LEFT_CLICK);

    // 飞到重庆上空
    viewer.camera.flyTo({
        destination: Cartesian3.fromDegrees(106.55, 29.57, 200000), // 降低高度以便更好地看到点位
        orientation: {
            heading: 0,
            pitch: -Math.PI/2,
            roll: 0
        }
    });
});
</script>
    
<style>
.point-popup {
    position: absolute;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 0;
    min-width: 200px;
    z-index: 1000;
}

.popup-header {
    background: #409EFF;
    color: white;
    padding: 8px 15px;
    border-radius: 4px 4px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.close-btn {
    cursor: pointer;
    font-size: 20px;
}

.close-btn:hover {
    opacity: 0.8;
}

.popup-content {
    padding: 15px;
}

.popup-content p {
    margin: 5px 0;
    color: #606266;
}
</style>